﻿using GKQC.Common;
using GKQC.DbHelper.Dao;
using GKQC.DbHelper.DbModels;
using GKQC.DbHelper.Services;
using GKQC.Language;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace GKQC
{
    public partial class FormSysParams : Form
    {
        UserModel user = null;
        AllDbContext dbContext = null;
        List<SysParamsModel> sysParams = null;
        FormStatus formStatus = FormStatus.Browser;
        readonly string countText = "記錄數：{0}";

        public FormSysParams(UserModel user, AllDbContext dbContext)
        {
            InitializeComponent();
            try
            {
                this.user = user;
                this.dbContext = dbContext;

                dataGridView1.RowPostPaint += DataGridView1_RowPostPaint;
                dataGridView1.AutoGenerateColumns = false;
                BindData();
                SetControlsEnable();
                LanguageHelper.SetControlLanguageText(this);
            }
            catch (Exception ex)
            {
                QMessageBox.Show(ex.Message);
                Logger.LogError(ex);
            }
        }

        private void DataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            DataGridViewSet.RowPostPaint(sender, e);
        }

        private void tsmEdit_Click(object sender, EventArgs e)
        {
            if (!UserRightService.CheckRight("FormSysParams", this.user, RightType.Modi))
            {
                return;
            }

            formStatus = FormStatus.Edit;
            SetControlsEnable();
        }

        private void tsmCancel_Click(object sender, EventArgs e)
        {
            formStatus = FormStatus.Browser;
            SetControlsEnable();
            BindData();
        }


        private void tsmSave_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;

                dataGridView1.EndEdit();
                List<SysParamsModel> listUpdate = new List<SysParamsModel>();
                foreach (DataGridViewRow r in dataGridView1.Rows)
                {
                    SysParamsModel model = r.DataBoundItem as SysParamsModel;
                    if (model == null) continue;
                    model.ModiDate = DateTime.Now;
                    model.ModiUser = user.UserCode;

                    if (model.Value == null) model.Value = string.Empty;

                    string msg = string.Empty;
                    if (!ValidatingRow(model, out msg))
                    {
                        QMessageBox.Show(msg, "驗證失敗");
                        return;
                    }

                    if (model.IsModified)
                        listUpdate.Add(model);// dbContext.QcDb.Updateable<SysParamsModel>(model).ExecuteCommand();     
                }

                if(listUpdate.Count > 0) dbContext.QcDb.Updateable<SysParamsModel>(listUpdate).ExecuteCommand();
               
                formStatus = FormStatus.Browser;
                SetControlsEnable();
                BindData();

                SysLogService.Log(dbContext, user, this, tsmEdit.Text
                    , string.Join(",", listUpdate.Select(l => l.Code).ToArray())
                    , string.Join(",", listUpdate.Select(l => l.Value).ToArray()));
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message,"異常S0002");
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }
        private void tsmDelete_Click(object sender, EventArgs e)
        {
            if(dataGridView1.SelectedRows.Count == 0)
            {
                QMessageBox.Show("請選擇要刪除的行", "提示");
            }


            int i = 0;
            string keys = string.Empty;
            string values = string.Empty;
            foreach (DataGridViewRow r in dataGridView1.SelectedRows)
            {
                SysParamsModel model = r.DataBoundItem as SysParamsModel;
                i += dbContext.QcDb.Deleteable<SysParamsModel>(model).ExecuteCommand();
                keys += model.Code;
                values += model.Value;
            }

            if(i>0)
            {
                QMessageBox.Show("成功刪除記錄 " + i.ToString() + " 條。", "提示");
                SysLogService.Log(dbContext, user, this, tsmDelete.Text, keys, values);
            }
            else
            {
                QMessageBox.Show("未刪除任何記錄");
            }
        }

        private void tsmExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }


        void SetControlsEnable()
        {
            if(formStatus == FormStatus.Browser)
            {
                tsmSave.Enabled = false;
                tsmCancel.Enabled = false;
                tsmEdit.Enabled = true;
                tsmExit.Enabled = true;
                tsmDelete.Enabled = true;
                dataGridView1.ReadOnly = true;
            }
            else
            {
                tsmSave.Enabled = true;
                tsmCancel.Enabled = true;
                tsmEdit.Enabled = false;
                tsmExit.Enabled = false;
                tsmDelete.Enabled = false;
                dataGridView1.ReadOnly = false;
            }
        }

        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            try
            {
                if (dataGridView1.Rows[e.RowIndex] == null) return;
                SysParamsModel model = dataGridView1.Rows[e.RowIndex].DataBoundItem as SysParamsModel;
                if (model == null) return;
                DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
                if (!(column.DataPropertyName == "Remark" || column.DataPropertyName == "Value"))
                {
                    e.Cancel = true;
                    return;
                }

                model.IsModified = true;
            }
            catch(Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message,"異常S0001");
            }
        }

        void BindData()
        {
            this.sysParams = this.dbContext.QcDb.Queryable<SysParamsModel>().ToList();
            dataGridView1.DataSource = new BindingList<SysParamsModel>(sysParams);
            toolStripStatusLabel1.Text = string.Format(countText, this.sysParams.Count.ToString());
        }

        bool ValidatingRow(SysParamsModel model,out string msg)
        {
            bool flag = true;
            msg = string.Empty;

            if (model == null) throw new ArgumentException("模型參數為空！");

            if(string.IsNullOrWhiteSpace(model.Code))
            {
                msg = "代號不能為空";
                return false;
            }

            return flag;
        }

        private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (formStatus == FormStatus.Browser) return;

            if(dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "Code")
            {
                string code = e.FormattedValue.ToString().ToLower();
                foreach(DataGridViewRow r in dataGridView1.Rows)
                {
                    if (r == dataGridView1.Rows[e.RowIndex]) continue;
                    if (r.Cells["ColCode"].Value == null) continue;

                    if(r.Cells["ColCode"].Value.ToString().ToLower()== code)
                    {
                        e.Cancel = true;
                        QMessageBox.Show("報表代號重複：" + r.Cells["ColCode"].Value.ToString());
                        return;
                    }
                }
            }
        }
    }
}
